package com.example.t1

import android.annotation.SuppressLint
import android.content.ComponentName
import android.content.Intent
import android.content.ServiceConnection
import android.os.Bundle
import android.os.Handler
import android.os.IBinder
import android.os.Message
import android.os.Messenger
import android.util.Log
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import com.example.t1.databinding.ActivityMainBinding

class MainActivity : AppCompatActivity() {

    private lateinit var binding: ActivityMainBinding
    private val MSG_SUM: Int = 0x110
    private val MSG_GPT: Int = 0x000
    private var mService: Messenger? = null
    private var isConn = false

    val comm = object : ServiceConnection {
        override fun onServiceConnected(
            name: ComponentName?, service: IBinder?
        ) {
            mService = Messenger(service)
            isConn = true
            binding.tvStatus.text = "已连接"
        }

        override fun onServiceDisconnected(name: ComponentName?) {
            mService = null
            isConn = false
            binding.tvStatus.text = "已断开"
        }
    }

    private val messenger = Messenger(
        @SuppressLint("HandlerLeak") object : Handler() {
            override fun handleMessage(msg: Message) {
                when (msg.what) {
                    MSG_SUM -> {
                        Log.d("aihongbo", "客户端SUM收到：${msg.arg2}")
                    }

                    MSG_GPT -> {
                        Log.d("aihongbo", "客户端GPT收到：${msg.data.getString("data")}")
                    }
                }
                super.handleMessage(msg)
            }
        })

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets ->
            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
            insets
        }

//        bindServiceInvoked()
        bindRemoteService()

        /**
         * 发送同应用进程消息
         */
        binding.floatingActionButton.setOnClickListener {
            val a = (Math.random() * 100).toInt()
            val b = (Math.random() * 100).toInt()

//            Log.d("aihongbo", "$a + $b = ")
            val msgFromClient = Message.obtain(null, MSG_SUM, a, b)
            msgFromClient.replyTo = messenger
            if (mService != null && isConn) {
                mService?.send(msgFromClient)
            }
        }

        /**
         * 发送跨应用进程消息
         */
        binding.floatingActionButton2.setOnClickListener {
            val a = (Math.random() * 100).toInt()
            val b = (Math.random() * 100).toInt()
            val msgFromClient = Message.obtain(null, MSG_GPT, a, b)
            msgFromClient.replyTo = messenger
            if (mService != null && isConn) {
                mService?.send(msgFromClient)
            }
        }
    }

    /**
     * 绑定同应用服务
     */
    fun bindServiceInvoked() {
//        val intent = Intent(this, MessengerService::class.java)
//        bindService(intent, comm, BIND_AUTO_CREATE)
    }

    /**
     * 绑定跨应用服务
     */
    fun bindRemoteService() {
        val intent = Intent("com.aihongbo.service.ai")
        intent.setPackage("com.aihongbo.service")
        val res: Boolean = bindService(intent, comm, BIND_AUTO_CREATE)
        if (!res) {
            throw Exception("连接服务失败!")
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        unbindService(comm)
    }
}